﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace OnlineCatalog.Controllers
{
    public class CatApiController : ApiController
    {
        private Model1Container db = new Model1Container();

        // GET api/CatApi
        public IEnumerable<CategoryModel> GetCategories()
        {
            return db.CategorySet.Select(it =>
                new CategoryModel
                {
                    Id = it.Id,
                    Name = it.Name,
                }).AsEnumerable();
        }

        // GET api/CatApi/5
        public CategoryModel GetCategory(int id)
        {
            CategoryModel category = db.CategorySet
                .Where(it => it.Id == id)
                .Select(it =>
                new CategoryModel
                {
                    Id = it.Id,
                    Name = it.Name,
                }).FirstOrDefault();
            if (category == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return category;
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }

    public class CategoryModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}